import axios from 'axios';
import VueAuth from '@websanova/vue-auth';
import VueAxios from 'vue-axios';
import util from './util'

class Init {
  static build(vue, router, store) {

    axios.defaults.baseURL = util.ajaxUrl.main;
    axios.defaults.timeout = 3000;
    vue.use(VueAxios, axios);

    vue.use(VueAuth, {
      auth: {
        request: function (req, token) {
          this.options.http._setHeaders.call(this, req, {Authorization: 'Bearer ' + token});
        },
        response: function (res) {
          return res.data.access_token;
        }
      },
      http: require('@websanova/vue-auth/drivers/http/axios.1.x.js'),
      router: require('@websanova/vue-auth/drivers/router/vue-router.2.x.js'),
      loginData: {fetchUser: true},
      fetchData: {
        url: util.ajaxUrl.auth + '/oauth/user',
        method: 'GET',
        success (res) {
          this.user(res.data);
        }
      },
      refreshData: {enabled: false}
    });

    this.inJectinterceptor(vue.prototype.$http,vue.prototype.$auth);

    vue.prototype.$flowHttp = axios.create({
      baseURL: util.ajaxUrl.flow,
      timeout: 30000
    });

    this.inJectinterceptor(vue.prototype.$flowHttp,vue.prototype.$auth);

    vue.prototype.$fileHttp = axios.create({
      baseURL: util.ajaxUrl.file,
      timeout: 30000
    });
    this.inJectinterceptor(vue.prototype.$fileHttp,vue.prototype.$auth);


    //roter
    router.beforeEach((to, from, next) => {
      if (to.name === 'login') {
        next();
      } else {
        if (vue.prototype.$auth.check()) {
          next();
        } else {
          next({
            path: '/login',
            query: {
              redirect: to.fullPath
            }
          });
        }
      }
    });
  }

  static inJectinterceptor(http,auth) {
    http.interceptors.request.use(
      config => {
        if (auth.check()) {
          config.headers.Authorization = `Bearer ${auth.token()}`;
        }
        return config;
      },
      err => {
        return Promise.reject(err);
      })
    // http response 拦截器
    http.interceptors.response.use(
      response => {
        return response;
      },
      error => {
        if (error.response) {
          switch (error.response.status) {
            case 401:
              if(error.response.data && error.response.data.error_description){
                error.message = '[账户未授权] '+error.response.data.error_description
              }
              auth.logout({
                redirect: {name: 'login'}
              });
              break;
            case 400:
              if(error.response.data && error.response.data.error_description && error.response.data.error_description=== '坏的凭证'){
                error.message = '登陆失败，请检查登陆账号和密码。'
              } else {
                error.message = error.response.data.message
              }
              break;
            case 403:
              error.message = '拒绝访问,请检查用户权限'
              break;
            case 404:
              error.message = `请求地址出错: ${error.response.config.url}`
              break
            case 408:
              error.message = '请求超时'
              break

            case 500:
              error.message = '服务器内部错误'
              break

            case 501:
              error.message = '服务未实现'
              break

            case 502:
              error.message = '网关错误'
              break

            case 503:
              error.message = '服务不可用'
              break

            case 504:
              error.message = '网关超时'
              break

            case 505:
              error.message = 'HTTP版本不受支持'
              break

            default:
          }
        }
        return Promise.reject(error);
      });
  }
}

export default Init;